package com.mk.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.mk.web.dto.PageInfo;
import com.mk.web.model.Flower;
import com.mk.web.service.FlowerService;
import com.mk.web.service.impl.FlowerServiceImpl;

/**
 * Created by WangChen on 2018/11/27 11:20.
 */
@WebServlet("/flower")
public class FlowerServlet extends HttpServlet {

    Logger logger = Logger.getLogger(FlowerServlet.class);
    private FlowerService flowerService = new FlowerServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String pageSizeStr = req.getParameter("pageSize");
        String pageNumberStr = req.getParameter("pageNumber");
        int pageSize = 2;
        if (pageSizeStr != null && !"".equals(pageSizeStr)){
            pageSize = Integer.parseInt(pageSizeStr);
        }
        int pageNumber = 1;
        if (pageNumberStr != null && !"".equals(pageNumberStr)){
            pageNumber = Integer.parseInt(pageNumberStr);
        }
        logger.info("pageSize:" + pageSizeStr + "--->pageNumber: " + pageNumberStr);
        PageInfo<Flower> page = null;
        try {
            page = flowerService.findByPage(pageSize, pageNumber);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // mybatis在解析 *Mapper.xml文件时会把异常包装成RuntimeException直接抛出,
        // 所有如果不手动捕获RuntimeException, 则后台不会打印异常信息
        // 须注意这个坑
        catch (RuntimeException e){
            // e.printStackTrace();
            logger.error("调用service方法异常:", e);
        }
        resp.setContentType("text/html;charset=utf-8");// [Flower{id=1, name='花1', price=5.2}, Flower{id=2, name='花2', price=6.3}]
        if (page != null ){
            resp.getWriter().write(page.getList().toString());
        }
    }
}
